package org.chris.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.chris.model.ProductModel;
import org.chris.service.ProductService;
import org.nutz.dao.Cnd;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.service.IdEntityService;

@IocBean(name="productService", fields={"dao"})
public class ProductServiceImpl extends IdEntityService<ProductModel> implements ProductService {
	
	public Map<String, Object> save(ProductModel model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			ProductModel query = this.dao().fetch(ProductModel.class, model.getId());
			if(null!=query){
				this.dao().update(model);
			}else{
				this.dao().insert(model);
			}
			result.put("type", "0");
			result.put("message", "保存成功");
		} catch (RuntimeException e) {
			result.put("type", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	public Map<String, Object> delete(String... ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			this.dao().clear(ProductModel.class, Cnd.where("id", "in", ids));
			result.put("type", "0");
			result.put("message", "删除成功");
		} catch (RuntimeException e) {
			result.put("type", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	public Map<String, Object> query(HttpServletRequest request,int rows,int page) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String name = request.getParameter("name");
			String gender = request.getParameter("gender");
			String firedate = request.getParameter("firedate");
			String dutyId = request.getParameter("dutyId");
			Criteria cn = Cnd.cri();
			if(!Strings.isEmpty(name)){
				cn.where().andEquals("name", name);
			}
			if(!Strings.isEmpty(gender)){
				cn.where().andEquals("gender", gender);
			}
			if(!Strings.isEmpty(firedate)){
				cn.where().and(new Static("firedate>=str_to_date('"+firedate+"','%Y-%m-%d')"));
			}
			if(!Strings.isEmpty(dutyId)){
				cn.where().andEquals("dutyId", dutyId);
			}
			Pager pager = new Pager();
			pager.setPageNumber(page);
			pager.setPageSize(rows);
			List<ProductModel> list = this.dao().query(ProductModel.class, cn,pager);
			for(ProductModel model : list){
				this.dao().fetchLinks(model, "duty");
			}
			result.put("total", this.dao().query(ProductModel.class, null).size());
			result.put("rows", list);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

}
